<?php
/**
 * 基础控制器
 */

namespace app\common\controller;


use think\Controller;
use think\facade\Session;
use app\common\model\ArtCate;
use app\common\model\Article;
use app\admin\common\model\Site;
class Base extends Controller
{

    /**
     * 初始化
     * 创建常量,公共方法
     * 在所有的方法之前被调用
     */
    protected function initialize()
    {
        $this->isOpen();
        $this->showNav();
        $this->showHot();

    }

    //防止重复登录
    public function logined(){
        if(Session::has('user_id')){
            $this->error('客官,您已经登陆了','index/index');
        }
    }

    //检查是否未登陆
    public function isLogin(){
        if(!Session::has('user_id')){
            $this->error('客官,您是不是忘记登陆了','user/login');
        }
    }


    //导航
    public function showNav(){
        $cate=ArtCate::all(function ($query){
            $query->where('status',1)->order('sort','asc');
        });
        $this->assign('cateList',$cate);
    }

    //判断网站是否开启
    protected function isOpen(){
        $site=Site::get(1);
        if($site['is_open']==0){
            exit('<h2 class="text-center">该网站正在维护中,请稍后进入</h2>');
        }
    }

    //判断能否进行注册
    public function isReg(){
        $site=Site::get(1);
        if($site['is_reg']==0){
            $this->error('本网站注册功能在维护中,请稍后进入');
        }
    }


    //无限极分类
    public function cateTree($cateRes){
        return $this->sort($cateRes);
    }

    private function sort($cateRes,$pid=0,$level=0){
        static $arr=array();
        foreach ($cateRes as $k => $v) {
            if($v['pid']==$pid){
                $v['level']=$level;
                $arr[]=$v;
                $this->sort($cateRes,$v['id'],$level+1);
            }
        }
        return $arr;
    }


    //找出所有热门文章
    public function showHot(){
        $hot=Article::order('pv','desc')->limit(6)->select();
        $this->assign('hot',$hot);
    }
}